package com.springboot.rabbitmq.listener;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.springboot.db.entity.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

/**
 * 用户mq监听器
 *
 * @author supu
 * @create 2019-01-25 12:48
 **/
@Log4j2
@Component
public class UserRabbitMqListener implements ChannelAwareMessageListener {


    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        if(message.getBody() == null){
            log.error("消息体内容为空");
            return;
        }

        String body = null;
        try {
            body = new String(message.getBody());
            User user = JSONObject.parseObject(body, User.class);
            log.warn("接收到的消息体：{}", JSONObject.toJSONString(user));
        } catch (Exception e) {
            log.error("消费消息：{} 异常：{}", body, e);
        } finally {
            // 当 SimpleMessageListenerContainer 设置 AcknowledgeMode 为 MANUAL 手动时，这里必须手动确认消息成功消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
